//
//  LoginViewController.m
//  shanHaiHuiApp
//
//  Created by DS on 2018/3/5.
//  Copyright © 2018年 徐双. All rights reserved.
//

#import "LoginViewController.h"
#import "HomeViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "qieappChooseView.h"
#import "LoginModel.h"

#import "HomeWithOUTViewController.h"


@interface LoginViewController ()

//公司标识和名字
Strong UIImageView * topImageView;
Strong UILabel * companyLabel;
//用户名
Strong UIImageView * nameImageView;
//Strong UITextField * nameTestField;
Strong UIView * namelineView;
//密码
Strong UIImageView * passwordImageView;
Strong UITextField * passTextField;
Strong UIImageView * eyeImageView;



Strong UIView * passLineView;
//店铺
Strong UIImageView * dingweiImageView;
Strong UIView *StoreLineView;
//登录按钮
Strong UIButton * loginBtn;

//接口数组
Strong NSMutableArray * listArr;

//选择框
Strong qieappChooseView * chooseView;

//店面模型
Strong LoginModel * loginModel;

//店面ID
Strong NSString * fidStr;

//用于存放药店名和编号
Strong NSMutableDictionary *fMemoFid;

Strong NSString * fmdeo;

//下一个页面显示什么标题
Strong NSString * nextTitle;

@end

//网络
@implementation LoginViewController (NetWorking)
//获取门店列表接口
- (void)getStoreData{
    [self showprogressHUD];
    NSDictionary *parameters = nil;
    [[AFAppDotNetAPIClient sharedClient] POST:@"mloginOrgList.do" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"code"] intValue] == 0) {
           self.loginModel = [[LoginModel alloc] init];
           for (NSDictionary * dic in responseObject[@"list"]) {
                [self.loginModel LoginModelWithDic:dic];
                [self.listArr addObject:self.loginModel.fMemo];
               [self.fMemoFid setObject:self.loginModel.fId forKey:self.loginModel.fMemo];
            }
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       [self hiddenProgressHUD];
        [self showError:error];
    }];
}
@end

@implementation LoginViewController

- (void)getData{
    [self showprogressHUD];
    NSDictionary *parameters = @{
                                 @"orgid":self.fidStr ? self.fidStr : [UserModel sharedInstanced].fid,
        
                                 @"userid":self.nameTestField.text,
                                 @"userpassword":[self md5:self.passTextField.text],
                                 @"client":@"IOS"
                                 };
    [[AFAppDotNetAPIClient sharedClient] POST:@"mloginCheck.do" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"code"] intValue] == 0) {
         
            [UserModel sharedInstanced].token = responseObject[@"token"];
            [UserModel sharedInstanced].userID = self.nameTestField.text ?: [UserModel sharedInstanced].userID;
            [UserModel sharedInstanced].fMemo = self.fmdeo ?: [UserModel sharedInstanced].fMemo;
            [UserModel sharedInstanced].fid = self.fidStr ?: [UserModel sharedInstanced].fid;
            
            [UserModel sharedInstanced].password = self.passTextField.text;
           
            HomeViewController * vc = [[HomeViewController alloc] init];
        
            vc.title = self.fmdeo;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            ShowMessage(responseObject[@"msg"]);
            [UserModel sharedInstanced].token = responseObject[@"token"];
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   [self getStoreData];
    self.navigationController.navigationBar.hidden = YES;
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]) {
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
        
        NSLog(@"第一次启动");
    }else{
        NSLog(@"不是第一次启动");
        
        self.nameTestField.text = [UserModel sharedInstanced].userID;
        
        if ([[UserModel sharedInstanced].fMemo isEqualToString:@""]) {
            
            [_StoreBtn setTitle: @"==请选择店面==" forState:UIControlStateNormal];
            
            
            
        }else{
           
            [_StoreBtn setTitle: [UserModel sharedInstanced].fMemo forState:UIControlStateNormal];
            
        }
        
       

//        NSString * title = [_StoreBtn currentTitle];
//
//        self.nextTitle = title;
    }
    
    
    if (self.nameTestField.text.length != 0 && self.passTextField.text.length !=0 && self.StoreBtn.titleLabel.text != 0) {
        
        _loginBtn.backgroundColor = getColor(navColor);
        
    }else{
        _loginBtn.backgroundColor = getColor(@"DADADA");
    }
    
    
    
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creationView];
    
    [self.nameTestField addTarget:self action:@selector(textChange) forControlEvents:UIControlEventEditingChanged];
    [self.passTextField addTarget:self action:@selector(textChange) forControlEvents:UIControlEventEditingChanged];
   
}


#pragma mark -- Action


// 当文本框的内容改变的时候就会调用
- (void)textChange
{
    
    if (self.nameTestField.text.length != 0 && self.passTextField.text.length !=0 && self.StoreBtn.titleLabel.text != 0) {
        
        _loginBtn.backgroundColor = getColor(navColor);
        
    }else{
        _loginBtn.backgroundColor = getColor(@"DADADA");
    }
    
}


//MD5加密
- (NSString *) md5:(NSString *) input {
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
}



- (void)tapClick:(UIGestureRecognizer *)sender{
    
    static int i = 0;
    i ++ ;
    if (i % 2 == 0) {
        self.eyeImageView.image = [UIImage imageNamed:@"yanjing"];
        NSString *tempPwdStr = self.passTextField.text;
        self.passTextField.text = @"";
        self.passTextField.secureTextEntry = NO;
        self.passTextField.text = tempPwdStr;
    }else{
        self.eyeImageView.image = [UIImage imageNamed:@"yangjing_guan"];
        NSString *tempPwdStr = self.passTextField.text;
        self.passTextField.text = @"";
        self.passTextField.secureTextEntry = YES;
        self.passTextField.text = tempPwdStr;
    }
}
- (void)StoreBtnClick:(UIButton *)sender{
    [self.view endEditing:YES];
    self.chooseView = [[qieappChooseView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) selectedHandle:^(NSString *str) {
      [_StoreBtn setTitle:str forState:UIControlStateNormal];
        
        self.fidStr = [self.fMemoFid objectForKey:str];
        
        self.fmdeo = str;
        
    }];
    
    self.chooseView.dataArray = self.listArr;
    [self.chooseView show];
}

- (void)loginBtnClick{
   
    [self.view endEditing:YES];
    if ([self.nameTestField.text isEqualToString:@""]) {
        ShowMessage(@"请输入用户名");
        return;
    }
    if ([self.passTextField.text isEqualToString:@""]) {
        ShowMessage(@"请输入密码");
        
        return;
    }

    if ([self.StoreBtn.titleLabel.text isEqualToString:@"==请选择店面=="]) {
        ShowMessage(@"请选择店面");
        return;
    }

    [self getData];
    
}




#pragma mark -- Init
- (void)creationView{
    //公司名称和图片
    [self.view addSubview:self.topImageView];
    [self.view addSubview:self.companyLabel];
    //用户名
    [self.view addSubview:self.nameImageView];
    [self.view addSubview:self.nameTestField];
    [self.view addSubview:self.namelineView];
    //密码
    [self.view addSubview:self.passwordImageView];
    [self.view addSubview:self.eyeImageView];
    
    
    [self.view addSubview:self.passTextField];
    [self.view addSubview:self.passLineView];
    //店铺
    [self.view addSubview:self.dingweiImageView];
    [self.view addSubview:self.StoreBtn];
    [self.view addSubview:self.StoreLineView];
    //登录
    [self.view addSubview:self.loginBtn];
    //布局
    [self layOutFrame];

}


- (UIImageView *)topImageView{
    if (!_topImageView) {
        _topImageView = [UIImageView new];
        _topImageView.contentMode = UIViewContentModeScaleAspectFit;
        _topImageView.image = [UIImage imageNamed:@"shanhaihuilogo"];
    }
    return _topImageView;
}

- (UILabel *)companyLabel{
    if (!_companyLabel) {
        _companyLabel = [[UILabel alloc] init];
        _companyLabel.font = DEF_FontSize_18;
        _companyLabel.textColor = getColor(@"EB3846");
        _companyLabel.textAlignment = NSTextAlignmentCenter;
        _companyLabel.text = @"山海慧购物系统";
    }
    return _companyLabel;
}
- (UIImageView *)nameImageView{
    if (!_nameImageView) {
        _nameImageView = [UIImageView new];
        _nameImageView.contentMode = UIViewContentModeScaleAspectFit;
        _nameImageView.image = [UIImage imageNamed:@"yingyeyuan"];
    }
    return _nameImageView;
}

- (UITextField *)nameTestField{
    if (!_nameTestField) {
        _nameTestField = [[UITextField alloc] init];
        _nameTestField.textColor = getColor(@"111111");
        _nameTestField.placeholder = @"请输入姓名";
        
      
        _nameTestField.font = DEF_FontSize_14;
        _nameTestField.clearButtonMode = UITextFieldViewModeAlways;
        
        //[_nameTestField addTarget:self action:@selector(textChange) forControlEvents:UIControlEventEditingChanged];
    }
    return _nameTestField;
}

- (UIView *)namelineView{
    if (!_namelineView) {
        _namelineView = [[UIView alloc] init];
        _namelineView.backgroundColor = getColor(@"F0F0F0");
       
    }
    return _namelineView;
}

- (UIImageView *)passwordImageView{
    if (!_passwordImageView) {
        _passwordImageView = [UIImageView new];
        _passwordImageView.contentMode = UIViewContentModeScaleAspectFit;
        _passwordImageView.image = [UIImage imageNamed:@"mima1"];
    }
    return _passwordImageView;
}


- (UIImageView *)eyeImageView{
    if (!_eyeImageView) {
        _eyeImageView = [UIImageView new];
        _eyeImageView.image = [UIImage imageNamed:@"yangjing_guan"];
        _eyeImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        [self.eyeImageView addGestureRecognizer:tap];
    }
    return _eyeImageView;
}

- (UITextField *)passTextField{
    if (!_passTextField) {
        _passTextField = [[UITextField alloc] init];
        _passTextField.textColor = getColor(@"111111");
        _passTextField.placeholder = @"请输入密码";
        _passTextField.font = DEF_FontSize_14;
        _passTextField.clearButtonMode = UITextFieldViewModeAlways;
        _passTextField.secureTextEntry = YES;
        _passTextField.text = [UserModel sharedInstanced].password;
        
       // [_passTextField addTarget:self action:@selector(textChange) forControlEvents:UIControlEventEditingChanged];
    }
    return _passTextField;
}

//李艳玲

- (UIView *)passLineView{
    if (!_passLineView) {
        _passLineView = [[UIView alloc] init];
        _passLineView.backgroundColor = getColor(@"F0F0F0");
    }
    return _passLineView;
}

- (UIImageView *)dingweiImageView{
    if (!_dingweiImageView) {
        _dingweiImageView = [UIImageView new];
        _dingweiImageView.contentMode = UIViewContentModeScaleAspectFit;
        _dingweiImageView.image = [UIImage imageNamed:@"dingwei"];
    }
    return _dingweiImageView;
}

- (UIButton *)StoreBtn{
    if (!_StoreBtn) {
        _StoreBtn = [[UIButton alloc] init];
        [_StoreBtn setTitleColor:getColor(@"323232") forState:UIControlStateNormal];
        [_StoreBtn addTarget:self action:@selector(StoreBtnClick:) forControlEvents:UIControlEventTouchUpInside];
         _StoreBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_StoreBtn setTitle:@"==请选择店面==" forState:UIControlStateNormal];
    }
    return _StoreBtn;
}

- (UIView *)StoreLineView{
    if (!_StoreLineView) {
        _StoreLineView = [[UIView alloc] init];
        _StoreLineView.backgroundColor = getColor(@"F0F0F0");
    }
    return _StoreLineView;
}

- (UIButton *)loginBtn{
    if (!_loginBtn) {
        _loginBtn = [[UIButton alloc] init];
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_loginBtn setTitleColor:getColor(@"FFFFFF") forState:UIControlStateNormal];
        _loginBtn.backgroundColor = getColor(@"CCCCCC");
        [_loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
        _loginBtn.layer.cornerRadius = 5;
        _loginBtn.layer.masksToBounds = YES;
        
    }
    return _loginBtn;
}


- (void)layOutFrame{
    ws(self)
    [self.topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(UNIT_HEIGHT(50));
        make.centerX.equalTo(self.view.mas_centerX);
        make.height.mas_equalTo(UNIT_HEIGHT(80));
        make.width.mas_equalTo(UNIT_WIDTH(85));
    }];
    
    [self.companyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakself.topImageView.mas_bottom).offset(UNIT_HEIGHT(15));
        make.centerX.mas_equalTo(weakself.topImageView.centerX);
        make.height.mas_equalTo(UNIT_HEIGHT(18));
        make.width.mas_equalTo(UNIT_WIDTH(SCREEN_WIDTH));
    }];
    [self.nameImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakself.companyLabel.mas_bottom).offset(UNIT_HEIGHT(55));
        make.left.mas_equalTo(UNIT_WIDTH(35));
        make.height.mas_equalTo(UNIT_HEIGHT(24));
        make.width.mas_equalTo(UNIT_WIDTH(21));
    }];
    
    [self.nameTestField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(UNIT_WIDTH(-31));
        make.left.mas_equalTo(weakself.nameImageView.mas_right).offset(UNIT_WIDTH(29));
        make.height.mas_equalTo(UNIT_HEIGHT(30));
        make.centerY.mas_equalTo(weakself.nameImageView.mas_centerY);
    }];
    [self.namelineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(UNIT_WIDTH(31));
        make.right.mas_equalTo(UNIT_WIDTH(-31));
        make.top.mas_equalTo(weakself.nameImageView.mas_bottom).offset(UNIT_HEIGHT(10));
        make.height.mas_equalTo(1);
    }];
    [self.passwordImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakself.namelineView.mas_bottom).offset(UNIT_HEIGHT(30));
        make.left.mas_equalTo(UNIT_WIDTH(35));
        make.height.mas_equalTo(UNIT_HEIGHT(23));
        make.width.mas_equalTo(UNIT_WIDTH(20));
    }];

    [self.eyeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(UNIT_WIDTH(-36));
        make.centerY.mas_equalTo(weakself.passwordImageView.mas_centerY);
        make.height.mas_equalTo(UNIT_HEIGHT(27));
        make.width.mas_equalTo(UNIT_WIDTH(25));
    }];
    
    [self.passTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakself.passwordImageView.mas_right).offset(UNIT_WIDTH(29));
        make.height.mas_equalTo(UNIT_HEIGHT(30));
        make.centerY.mas_equalTo(weakself.passwordImageView.mas_centerY);
        make.right.mas_equalTo(weakself.eyeImageView.mas_left).offset(UNIT_WIDTH(-10));
    }];
   
    [self.passLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(UNIT_WIDTH(31));
        make.right.mas_equalTo(UNIT_WIDTH(-31));
        make.top.mas_equalTo(weakself.passwordImageView.mas_bottom).offset(UNIT_HEIGHT(10));
        make.height.mas_equalTo(1);
    }];
    
    [self.dingweiImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakself.passLineView.mas_bottom).offset(UNIT_HEIGHT(30));
        make.left.mas_equalTo(UNIT_WIDTH(35));
        make.height.mas_equalTo(UNIT_HEIGHT(23));
        make.width.mas_equalTo(UNIT_WIDTH(20));
    }];
    
    [self.StoreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(UNIT_WIDTH(-31));
        make.left.mas_equalTo(weakself.dingweiImageView.mas_right).offset(UNIT_WIDTH(29));
        make.height.mas_equalTo(UNIT_HEIGHT(30));
        make.centerY.mas_equalTo(weakself.dingweiImageView.mas_centerY);
    }];
    [self.StoreLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(UNIT_WIDTH(31));
        make.right.mas_equalTo(UNIT_WIDTH(-31));
        make.top.mas_equalTo(weakself.dingweiImageView.mas_bottom).offset(UNIT_HEIGHT(10));
        make.height.mas_equalTo(1);
    }];
    
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakself.StoreLineView.mas_bottom).offset(UNIT_HEIGHT(40));
        make.left.mas_equalTo(UNIT_WIDTH(40));
        make.right.mas_equalTo(UNIT_WIDTH(-40));
        make.height.mas_equalTo(UNIT_HEIGHT(40));
    }];
}

- (NSMutableArray *)listArr{
    if (!_listArr) {
        _listArr = @[
                     ].mutableCopy;
    }
    return _listArr;
}

- (NSMutableDictionary *)fMemoFid{
    if (!_fMemoFid) {
        _fMemoFid = [NSMutableDictionary dictionary];
    }
    return _fMemoFid;
}


@end
